package servlet1;

import entity.UserLogin;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;


//登录
@WebServlet("/login")
public class loginServlet extends HttpServlet {

    private UserService UserSer = new UserService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String acc = req.getParameter("account");
        String pwd = req.getParameter("password");
        UserLogin login =new UserLogin();
        login.setAccount(acc);
        UserLogin user = UserSer.login(acc , pwd);
        if (user != null){
            req.getSession().setAttribute("msg", "登录成功");
            String token = UUID.randomUUID().toString();
            // 把token和用户进行绑定
            UserSer.setToken(user.getId(), token);
            // 把token放到cookie中存储下来
            Cookie cookie = new Cookie("TOKEN", token);
            cookie.setMaxAge(Integer.MAX_VALUE);
            // 把cookie传给客户端
            resp.addCookie(cookie);

            resp.sendRedirect( "/page.jsp");

        }else{
        resp.sendRedirect( "/login.jsp");

        }
    }
}